from datetime import date

from tqsdk import TqApi, TqAuth
from tqsdk import TqSim, TqBacktest, BacktestFinished
from tqsdk.ta import MACD, BOLL


# 在附图中画 macd 指标
def calc_macd_klines(klines):
    # 计算 macd 指标
    macd = MACD(klines, 12, 26, 9)
    # 用 K 线图模拟 MACD 指标柱状图
    klines["MACD.open"] = 0.0
    klines["MACD.close"] = macd["bar"]
    klines["MACD.high"] = klines["MACD.close"].where(klines["MACD.close"] > 0, 0)
    klines["MACD.low"] = klines["MACD.close"].where(klines["MACD.close"] < 0, 0)
    klines["MACD.board"] = "MACD"

    # 在 board=MACD 上添加 diff、dea 线
    klines["diff"] = macd["diff"]
    klines["diff.board"] = "MACD"
    klines["diff.color"] = "gray"

    klines["dea"] = macd["dea"]
    klines["dea.board"] = "MACD"
    klines["dea.color"] = "rgb(255,128,0)"

    try:
        tqsim = TqSim(init_balance=100000)
        api = TqApi(tqsim,
        auth=TqAuth("15842676013@m.com", "482737900Wtxdy"),
        web_gui=":58538",
        backtest=TqBacktest(start_dt=date(2023, 8, 11), end_dt=date(2023, 12, 11)))
        main_code = (api.get_quote('KQ.m@CZCE.oi')).underlying_symbol# 主力合约码
        klines = api.get_kline_serial(main_code, 60 * 60, data_length=30) # K线
        quote = api.get_quote(main_code)# 行情
        account = api.get_account()# 账户
        position = api.get_position(main_code)# 持仓
        while True:
            api.wait_update()
            if api.is_changing(klines):
                # 主图指标线
                boll = BOLL(klines, 26, 2)
                klines["top"] = boll.top
                klines["mid"] = boll.mid
                klines["bottom"] = boll.bottom
                # 附图指标线
                calc_macd_klines(klines)

    except BacktestFinished as e:
                print(e)
                # 回测结束时会执行这里的代码
                api.close()

    print(tqsim.trade_log)# 回测的详细信息

    print(tqsim.tqsdk_stat)# 回测时间内账户交易信息统计结果，其中包含以下字段

# init_balance 起始资金

# balance 结束资金

# max_drawdown 最大回撤

# profit_loss_ratio 盈亏额比例

# winning_rate 胜率

# ror 收益率 作者：WC_MrsFu123 https://www.bilibili.com/read/cv18869734/ 出处：bilibili
if __name__ == '__main__':
    calc_macd_klines()